﻿using System;
using System.Collections.Generic;
using System.Text;
using Model;
using System.Data;
using DALFactory.DataBase;
using AppToolKit.Core.Context.Spring;
using System.IO;
using Utility;
using Common.Logging;
using BLL.Action.Core.Caching;

namespace BLL.Business
{
    [AutoWiring]
    public class EntityBusinessDao
    {
        ILog log = LogManager.GetLogger(typeof(EntityBusinessDao));

        [AutoWiring]
        public ClientCache Cache { get; set; }

        [AutoWiring]
        public AccessHelper AccessHelperHolder { get; set; }

        protected string path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, string.Format("Config{0}Mapping{0}", Path.DirectorySeparatorChar));

        public DataRow Load(Model.EntityKey key, string table)
        {
            string strSql = string.Format("select * from {0} where {1}", table, key.ToString());

            DataSet ds = AccessHelperHolder.GetDataSet(CommandType.Text, strSql);

            if (ds.Tables[0].Rows.Count == 1)
                return ds.Tables[0].Rows[0];
            else
                throw new Exception("不存在");
        }
        public void Delete(Model.EntityKey key, string table)
        {
            string strSql = string.Format("delete from {0} where {1}", table, key.ToString());

            AccessHelperHolder.ExecuteNonQuery(CommandType.Text, strSql);
        }

        public void Save(DataTrans data)
        {
            string col = string.Empty;
            string value = string.Empty;
            foreach (ColumnDefine column in data.Entity.PrimaryKey.Keys)
            {

                col += string.Format(",{0}", column.Column);
                if (column.Type == DataType.INT)
                    value += string.Format(",{0}", column.Value);
                else
                    value += string.Format(",'{0}'", column.Value);
            }
            foreach (ColumnDefine column in data.Entity.Cols)
            {

                col += string.Format(",{0}", column.Column);
                if (column.Type == DataType.INT)
                    value += string.Format(",{0}", column.Value);
                else
                    value += string.Format(",'{0}'", column.Value);
            }
            col = StringHelper.StrStartSubstring(col, ",");
            value = StringHelper.StrStartSubstring(value, ",");
            //if (col.Trim().StartsWith(","))
            //    col = col.Trim().Substring(1);
            //if (value.Trim().StartsWith(","))
            //    value = value.Trim().Substring(1);

            string strSql = string.Format("insert  {0} ({1} )values({2})", data.Entity.TalbeName, col, value);
            log.Debug("str:" + strSql);
            AccessHelperHolder.ExecuteNonQuery(CommandType.Text, strSql);
        }
        public void Update(DataTrans data)
        {
            string col = string.Empty;

            foreach (ColumnDefine column in data.Entity.Cols)
            {

                col += string.Format(",{0}", column.ToString());

            }

            string condition = data.Entity.PrimaryKey.ToString();

            if (col.Trim().StartsWith(","))
                col = col.Trim().Substring(1);


            string strSql = string.Format("update {0} set {1}  where {2} ", data.Entity.TalbeName, col, condition);

            AccessHelperHolder.ExecuteNonQuery(CommandType.Text, strSql);
        }
        public object Create(string XmlName)
        {
            try
            {
                //return Caching.CacheHelper.Cache(Cache,"TABAL_"+XmlName,delegate {return  XmlReadWriteHelper.Deserialize(typeof(DataTrans), GetXml(XmlName));});
                return XmlReadWriteHelper.Deserialize(typeof(DataTrans), GetXml(XmlName));
            }
            catch (Exception ex)
            {
                log.Debug(ex);
            }
            return null;
        }


        private string GetXml(string XmlName)
        {
            return string.Format("{0}{1}.xml", path, XmlName);
        }
    }
}
